// 默认设置
const defaultSettings = {
  notifications: {
    enabled: true,
    timeout: 5000 // 通知显示时间，单位毫秒
  },
  player: {
    useCustom: false,
    defaultPlayer: 'https://m3u8play.com/?url=',
    customPlayerUrl: ''
  },
  downloader: {
    useCustom: false,
    defaultDownloader: 'https://tools.thatwind.com/tool/m3u8downloader#',
    customDownloaderUrl: '',
    autoOpen: false
  },
  filters: {
    enabled: false,
    rules: []
  },
  storage: {
    autoClear: false,
    maxItems: 100,
    clearAfterDays: 7
  }
};

// 当前设置
let currentSettings = {};

// 初始化
async function initialize() {
  // 加载设置
  await loadSettings();
  
  // 更新扩展图标
  await updateBadge();
  
  // 设置自动清理定时器
  setupAutoCleaner();
}

// 加载设置
async function loadSettings() {
  const result = await chrome.storage.sync.get({ settings: defaultSettings });
  currentSettings = result.settings;
}

// 设置自动清理定时器
function setupAutoCleaner() {
  // 每天检查一次是否需要清理
  setInterval(async () => {
    if (currentSettings.storage.autoClear) {
      await cleanOldLinks();
    }
  }, 24 * 60 * 60 * 1000); // 24小时
  
  // 立即执行一次清理
  if (currentSettings.storage.autoClear) {
    cleanOldLinks();
  }
}

// 清理旧链接
async function cleanOldLinks() {
  const result = await chrome.storage.local.get({ m3u8Links: [] });
  let links = result.m3u8Links;
  
  if (links.length === 0) {
    return;
  }
  
  const now = Date.now();
  let hasChanges = false;
  
  // 按时间清理
  if (currentSettings.storage.clearAfterDays > 0) {
    const cutoffTime = now - (currentSettings.storage.clearAfterDays * 24 * 60 * 60 * 1000);
    const oldLength = links.length;
    links = links.filter(link => link.timestamp > cutoffTime);
    
    if (links.length < oldLength) {
      hasChanges = true;
    }
  }
  
  // 按数量清理
  if (currentSettings.storage.maxItems > 0 && links.length > currentSettings.storage.maxItems) {
    // 按时间排序
    links.sort((a, b) => b.timestamp - a.timestamp);
    
    // 只保留指定数量的链接
    links = links.slice(0, currentSettings.storage.maxItems);
    hasChanges = true;
  }
  
  // 如果有变化，保存更新后的链接
  if (hasChanges) {
    await chrome.storage.local.set({ m3u8Links: links });
    await updateBadge();
  }
}

// 更新扩展图标上的徽章
async function updateBadge() {
  const result = await chrome.storage.local.get({ m3u8Links: [] });
  const count = result.m3u8Links.length;
  
  if (count > 0) {
    // 显示链接数量
    chrome.action.setBadgeText({ text: count.toString() });
    chrome.action.setBadgeBackgroundColor({ color: '#4285f4' });
  } else {
    // 清除徽章
    chrome.action.setBadgeText({ text: '' });
  }
}

// 检查链接是否符合过滤规则
function checkFilters(url) {
  if (!currentSettings.filters.enabled || !currentSettings.filters.rules || currentSettings.filters.rules.length === 0) {
    return true; // 如果未启用过滤或没有规则，则接受所有链接
  }
  
  // 检查每个规则
  for (const rule of currentSettings.filters.rules) {
    if (!rule) continue;
    
    // 排除规则
    if (rule.startsWith('!')) {
      const pattern = rule.substring(1);
      try {
        const regex = new RegExp(pattern);
        if (regex.test(url)) {
          return false; // 匹配排除规则，拒绝链接
        }
      } catch (e) {
        console.error('无效的正则表达式:', pattern, e);
      }
    } 
    // 包含规则
    else {
      try {
        const regex = new RegExp(rule);
        if (regex.test(url)) {
          return true; // 匹配包含规则，接受链接
        }
      } catch (e) {
        console.error('无效的正则表达式:', rule, e);
      }
    }
  }
  
  // 如果有包含规则但都不匹配，则拒绝链接
  const hasIncludeRule = currentSettings.filters.rules.some(rule => !rule.startsWith('!'));
  return !hasIncludeRule;
}

// 添加M3U8链接
async function addM3U8Link(url, pageUrl, pageTitle) {
  // 检查链接是否符合过滤规则
  if (!checkFilters(url)) {
    console.log('链接被过滤规则拒绝:', url);
    return false;
  }
  
  // 获取当前保存的链接
  const result = await chrome.storage.local.get({ m3u8Links: [] });
  let links = result.m3u8Links;
  
  // 检查链接是否已存在
  const existingIndex = links.findIndex(link => link.url === url);
  
  if (existingIndex !== -1) {
    // 更新现有链接的时间戳和页面信息
    links[existingIndex].timestamp = Date.now();
    links[existingIndex].pageUrl = pageUrl;
    links[existingIndex].pageTitle = pageTitle;
  } else {
    // 添加新链接
    links.push({
      url: url,
      pageUrl: pageUrl,
      pageTitle: pageTitle,
      timestamp: Date.now()
    });
  }
  
  // 保存更新后的链接
  await chrome.storage.local.set({ m3u8Links: links });
  
  // 更新扩展图标
  await updateBadge();
  
  // 如果启用了通知，显示通知
  if (currentSettings.notifications.enabled) {
    showNotification(url, pageTitle);
  }
  
  // 如果启用了自动打开下载器，打开下载页面
  if (currentSettings.downloader.autoOpen) {
    openDownloader(url);
  }
  
  return true;
}

// 显示通知
function showNotification(url, pageTitle) {
  chrome.notifications.create({
    type: 'basic',
    iconUrl: 'icons/icon128.png',
    title: '检测到M3U8链接',
    message: `在页面 "${pageTitle || '未知页面'}" 中检测到M3U8链接`,
    buttons: [
      { title: '播放' },
      { title: '下载' }
    ],
    priority: 1,
    silent: false
  }, notificationId => {
    // 保存通知ID和URL的映射关系，用于处理按钮点击
    notificationUrlMap[notificationId] = url;
    
    // 如果设置了通知超时，则自动关闭通知
    if (currentSettings.notifications.timeout > 0) {
      setTimeout(() => {
        chrome.notifications.clear(notificationId);
        delete notificationUrlMap[notificationId];
      }, currentSettings.notifications.timeout);
    }
  });
}

// 通知ID和URL的映射关系
const notificationUrlMap = {};

// 打开播放器
function openPlayer(url) {
  const playerUrl = currentSettings.player.useCustom && currentSettings.player.customPlayerUrl
    ? currentSettings.player.customPlayerUrl.replace('{url}', encodeURIComponent(url))
    : currentSettings.player.defaultPlayer + encodeURIComponent(url);
  
  chrome.tabs.create({ url: playerUrl });
}

// 打开下载器
function openDownloader(url) {
  const downloaderUrl = currentSettings.downloader.useCustom && currentSettings.downloader.customDownloaderUrl
    ? currentSettings.downloader.customDownloaderUrl.replace('{url}', encodeURIComponent(url))
    : currentSettings.downloader.defaultDownloader + encodeURIComponent(url);
  
  chrome.tabs.create({ url: downloaderUrl });
}

// 监听来自内容脚本的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'foundM3U8') {
    // 处理检测到的M3U8链接
    addM3U8Link(message.url, message.pageUrl, message.pageTitle)
      .then(success => {
        sendResponse({ success });
      })
      .catch(error => {
        console.error('处理M3U8链接失败:', error);
        sendResponse({ success: false, error: error.message });
      });
    
    // 返回true表示将异步发送响应
    return true;
  } else if (message.action === 'updateBadge') {
    // 更新扩展图标上的徽章
    updateBadge()
      .then(() => {
        sendResponse({ success: true });
      })
      .catch(error => {
        console.error('更新徽章失败:', error);
        sendResponse({ success: false, error: error.message });
      });
    
    // 返回true表示将异步发送响应
    return true;
  }
});

// 监听通知按钮点击
chrome.notifications.onButtonClicked.addListener((notificationId, buttonIndex) => {
  const url = notificationUrlMap[notificationId];
  
  if (!url) {
    return;
  }
  
  // 按钮索引：0=播放，1=下载
  if (buttonIndex === 0) {
    openPlayer(url);
  } else if (buttonIndex === 1) {
    openDownloader(url);
  }
  
  // 清除通知
  chrome.notifications.clear(notificationId);
  delete notificationUrlMap[notificationId];
});

// 监听通知关闭
chrome.notifications.onClosed.addListener(notificationId => {
  delete notificationUrlMap[notificationId];
});

// 监听存储变化
chrome.storage.onChanged.addListener((changes, areaName) => {
  if (areaName === 'sync' && changes.settings) {
    // 更新当前设置
    currentSettings = changes.settings.newValue;
  }
});

// 初始化
initialize();